<?php
/**
 * ============================================================================
 * Copyright (c) 2015-2020 贵州大师兄信息技术有限公司 All rights reserved.
 * siteַ: https://www.gzdsx.cn
 * ============================================================================
 * @author:     David Song<songdewei@163.com>
 * @version:    v1.0.0
 * ---------------------------------------------
 * Date: 2020/5/28
 * Time: 9:39 上午
 */

namespace App\Traits\Order;


use App\Jobs\OrderRefundMoney;
use App\Models\Refund;
use Illuminate\Http\Request;

trait RefundProcessor
{
    public function get(Request $request)
    {
        $refund = Refund::findOrFail($request->input('refund_id'));
        $refund->load(['order', 'images', 'orderItem']);
        return ajaxReturn(['refund' => $refund]);
    }

    public function batchget(Request $request)
    {
        $query = Refund::query();
        if (is_numeric($state = $request->input('refund_state'))){
            $query->where('refund_state',$state);
        }
        return ajaxReturn([
            'total' => $query->count(),
            'items' => $query->offset($request->input('offset', 0))
                ->limit($request->input('count', 15))->orderByDesc('refund_id')->get()
        ]);
    }

    public function delete(Request $request)
    {
        Refund::whereKey($request->input('items', []))->delete();
        return ajaxReturn();
    }

    /**
     * 处理退款
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function process(Request $request)
    {
        $refund = Refund::findOrFail($request->input('refund_id'));
        $action_type = $request->input('action_type');

        //同意退款
        if ($action_type == 1){
            if ($order = $refund->order) {
                $order->refund_state = 2;
                $order->refund_at = now();
                $order->order_state = 5;
                $order->closed = 1;
                $order->closed_at = now();
                $order->save();

                if ($transaction = $order->transaction) {
                    dispatch(new OrderRefundMoney($transaction, $refund));
                }
            }
            $refund->refund_state = 5;
            $refund->save();
        }

        //同意退货
        if ($action_type == 2){
            $refund->refund_state = 3;
            $refund->save();
        }

        //拒绝退款
        if ($action_type == 3){
            $refund->refund_state = 2;
            $refund->save();
        }

        return ajaxReturn(['refund' => $refund]);
    }
}
